package cn.monkey.io.transport.netty.server.codec.protocol.tcp.mqtt;

import cn.monkey.io.transport.netty.server.codec.protocol.tcp.TcpServerProtocolPredicate;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.ReferenceCountUtil;


public interface MqttServerProtocolPredicate extends TcpServerProtocolPredicate {
    MqttServerProtocolPredicate INSTANCE = new MqttServerProtocolPredicate() {
    };


    @Override
    default boolean test0(SocketChannel channel, ByteBuf data) {
        ByteBuf byteBuf = Unpooled.copiedBuffer(data);
        try {
            byte[] array = byteBuf.array();
            boolean hasMqttFirstWord = false;
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                if ("MQTT".contentEquals(sb) || "MQIsdp".contentEquals(sb)) {
                    return true;
                }
                if (hasMqttFirstWord) {
                    // MQIsdp
                    if (b != 'Q' && b != 'T' && b != 'I' && b != 's' & b != 'd' & b != 'p') {
                        return false;
                    }
                    sb.append((char) b);
                }
                if (b == 'M') {
                    hasMqttFirstWord = true;
                    sb.append((char) b);
                }
            }
        } finally {
            ReferenceCountUtil.release(byteBuf);
        }
        return false;
    }
}
